import React, {Component} from 'react'
import {View, Text, ScrollView, Dimensions, StyleSheet, TouchableOpacity, Modal, Image, Button} from 'react-native'
import Spinner from 'react-native-spinkit'
import Icon from 'react-native-vector-icons/Ionicons'
import {connect} from 'react-redux'
import filterSentenceForAnalysis, {checkName, getNormalPhone} from '../../helpers/contentForIbm'
import Recording from 'react-native-recording'
import {fsReadPath} from '../../helpers/fsHelper'
import styles from '../../config/styles'

var Sound = require('react-native-sound')
const screenWidth = Dimensions.get('window').width

class Challenge extends Component {
    static navigationOptions = ({ navigation }) => {
        return {
            headerRight: <View />
        }
    }

    constructor (props) {
        super(props)
        const params = props.navigation.state.params
        this.state = {
            sentences: params.sentences,
            unreadSentences: params.sentences,
            recording: false,
            ws: null,
            dataForReport: [],
            modalVisible: false,
            wsLocked: false
        }
    }

    // componentWillReceiveProps (nextProps) {
    //     const recording = nextProps.recording
    //     try {
    //         if (this.state.ws != null && this.state.ws.readyState === 1 && recording != this.props.recording) {
    //             this.state.ws.send(JSON.stringify({
    //                 stream_type: 'array',
    //                 stream: recording.stream,
    //                 status: 'process'
    //             }))
    //         }
    //     } catch(err) {
    //         console.log(err)
    //     }
    // }

    componentDidMount () {
        this.listener = Recording.addRecordingEventListener((data) => {
            if (this.state.ws != null && this.state.ws.readyState === 1) {
                this.state.ws.send(JSON.stringify({
                    stream_type: 'array',
                    stream: data,
                    status: 'process'
                }))
            }
        })
    }

    componentWillUnmount () {
        this.listener.remove()
    }

     //录音按钮的icon模板
     recorderStatusIcon = () => {
        if (this.state.recording) {
            return(
                <View style={[styles.large_icon, {backgroundColor: '#00FF00'}]}>
                    <View style={styles.icon_inner_container}>
                        <Spinner type={'Wave'} color={'white'} />
                    </View>
                </View>   
            )
        } else {
            return(
                <View style={[styles.large_icon]}>
                    <View style={styles.icon_inner_container}>
                        <Icon name={'ios-mic-outline'} size={45} color={'white'} />
                    </View>
                </View>   
            )
        }
    }

    sentencesTemplate = () => {
        return(
            <ScrollView style={{flex: 1}}>
                {this.state.unreadSentences.map((sentence, index) => {
                    return (
                        <View key={index} style={{alignItems: 'center', marginTop: 30}}>
                            <Text style={{
                                fontSize: 20,
                                fontWeight: index == 0 ? 'bold' : 'normal',
                                color: index == 0 ? 'black' : 'grey'
                            }}>
                                {sentence.content}
                            </Text>
                        </View>
                    )    
                })}
            </ScrollView>
        )
    }

    reportModalTemplate = () => {
        let score = 0
        let scores = this.state.dataForReport.forEach((r) => {score += r.score})
        let avg = Math.floor(score / this.state.sentences.length)
        return (
            <Modal
                animationType={'slide'}
                visible={this.state.modalVisible}
                transparent={true}
                onRequestClose={() => {}}                
            >
                <View style={{backgroundColor: 'white', flex: 1, alignItems: 'center', padding: 10}}>
                    <Image
                        resizeMode={'contain'}
                        source={require('../../assets/images/challenge-good-img.png')}
                        style={{height: screenWidth -20, width: screenWidth- 20}}
                    />
                    <Text style={{fontSize: 20}}>平均得分</Text>
                    <Text style={{color: 'orange', fontSize: 25}}>
                        {avg}
                    </Text>
                    <TouchableOpacity style={[styles.reportButton, {backgroundColor: 'green'}]} onPress={this.rechallenge}>
                        <Text style={{fontSize: 15, color: 'white'}}>重新挑战</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={[styles.reportButton, {backgroundColor: 'orange'}]} onPress={this.viewReport}>
                        <Text style={{fontSize: 15, color: 'white'}}>成绩单</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={[styles.reportButton, {backgroundColor: '#00BBFF'}]} onPress={this.completeChallenge}>
                        <Text style={{fontSize: 15, color: 'white'}}>完成</Text>
                    </TouchableOpacity>
                   
                </View>
            </Modal>
        )
    }

    //一次录制完成后
    afterRecord = async (data, timeStamp) => {
        const {user, settings} = this.props.user
        const {score_weighting} = settings
        let score
        //先算分数
        if (data.pron_score >= score_weighting.great) {
            score = 100
        } else {
            score = 100 * data.pron_score / score_weighting.great
        }

        let _words = []
        //新版接口，多了一层phrases，拆掉
        data.phrases.forEach(e => _words.push(...e.words))

        _words = _words.filter((w) => {
            return w.word != "<SIL>"
        })
        let _sentences = this.currentSentence().content.split(" ")
        let _ibmSentences = []
        _sentences.forEach((s, s_index) => {
            let _word_in_ibm = _words.filter((w, w_index) => {
                return s_index == w_index
            })[0]
            
            _ibmSentences.push({
                word: s,
                score: _word_in_ibm == undefined ? null : _word_in_ibm.pron_score,
            })
        })
        
        const _playbackUrl = await fsReadPath(`https://s3.cn-north-1.amazonaws.com.cn/oraltest/audios/${user.login_name}_${timeStamp}.wav`)
        this.state.dataForReport.push({
            score: Math.floor(score),
            ibmSentences: _ibmSentences,
            playbackUrl: _playbackUrl
        })
    }

    //重新挑战
    rechallenge = () => {
        this.setState({
            modalVisible: false,
            unreadSentences: this.state.sentences,
            dataForReport: []
        })
    }

    //查看报告
    viewReport = () => {
        this.props.navigation.navigate('challenger_report', {
            dataForReport: this.state.dataForReport
        })
        this.rechallenge()
    }

    //完成挑战，返回上一个页面
    completeChallenge = () => {
        this.setState({modalVisible: false})
        this.props.navigation.goBack(null)
    }

    //当前在读的sentence
    currentSentence = () => {
        return this.state.unreadSentences[0]
    }

    //计算报告
    calculateReport = () => {
        this.setState({modalVisible: true})
    }
    
    //按下录音
    onRecordPress = () => {
        Sound.setCategory('Record')
        if (this.state.recording) {
            this.setState({recording: false})
            if (this.state.ws != null && this.state.ws.readyState === 1) {
                this.state.ws.send(JSON.stringify({
                    status: 'end'
                }))
            }
            Recording.stop()
           
            //如果此时没有未读的sentence了，出报告
            if (this.state.unreadSentences.length == 1) this.calculateReport()
        } else {
            this.setState({recording: true}, () => {
                if (this.state.wsLocked == true) {this.setState({recording: false});return}
                //连接成功后，锁定，不能连续点击
               this.state.wsLocked = true
               setTimeout(() => {this.state.wsLocked = false}, 150)
               let sentence = this.currentSentence()
               if (sentence == undefined) return
               this.state.recording = true
               let timeStamp = new Date().getTime()
               let _content = filterSentenceForAnalysis(sentence.content, sentence.grouped_content)
               let {user} = this.props.user
               this.state.ws = new WebSocket(
                   `ws://${user.login_name}:${timeStamp}@54.223.255.113:8008?` +
                   `content=${encodeURI(_content)}&id=${user.login_name}&timestamp=${timeStamp}&buffer_size=8192`
               )
   
               this.state.ws.onopen = (e) => {
                   Recording.init({bufferSize: 8192,sampleRate: 16000})
                   Recording.start()
               }
   
               this.state.onerror = (e) => {
                   try {
                       this.state.ws.close()
                       this.state.ws = null
                   } catch (e) {}
               }
   
               this.state.ws.onmessage = async (e) => {
                   /* 创建一个ibm结果的对象，之后需要在成绩单页面用到
                       对象的形式如下
                       {
                           words: [...],
                           url: '',
                           score: 0
                       }
                   */
                   const _data = JSON.parse(e.data)
                   if (_data.code == "200") {
                       this.afterRecord(_data.body, timeStamp)
                   } else {
                       const _playbackUrl = await fsReadPath(`https://s3.cn-north-1.amazonaws.com.cn/oraltest/audios/${user.login_name}_${timeStamp}.wav`)
                       this.state.dataForReport.push({
                           score: 0,
                           playbackUrl: _playbackUrl,
                           ibmSentences: [{
                               word: sentence.content,
                               score: 0
                           }]
                       })
                   }
                   if (this.state.ws != null && this.state.ws.readyState === 1) {
                       this.state.ws.close()
                       this.state.ws = null
                   }
                 
                   this.setState({unreadSentences: this.state.unreadSentences.slice(1)})  
               }
            })

        }
    }

    render () {
        return(
            <View style={{flex: 1, backgroundColor: 'white'}}>
                {this.sentencesTemplate()}
                <View style={{justifyContent: 'center', alignItems: 'center', margin: 15}}>
                    <TouchableOpacity
                        //onPressIn={this.onRecordPress}
                        onPress={this.onRecordPress}
                        //onPressOut={this.onRecordPress}
                        // delayPressOut={100}
                        // delayPressIn={0}
                     >
                       {this.recorderStatusIcon()}
                   </TouchableOpacity>
                   {this.reportModalTemplate()}
                </View>
            </View>
        )
    }
}

const mapStateToProps = (state) => {
    return {
       user: state.user
    }
}

export default connect(mapStateToProps)(Challenge)